<?php

namespace app\search\controller;

use app\lib\enum\Status;
use think\Controller;
use think\Exception;
use think\Log;

class Common extends Controller
{
    //微信支付结果通知与处理
    public function notify() {
        $xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //进行支付成功后的处理
        $result = $this->handleNotify($data);
        if ($result) {
            file_put_contents(STATIC_PATH . "pay.txt", "支付成功");
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        } else {
            file_put_contents(STATIC_PATH . "pay.txt", "支付失败");
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>";
        }
    }

    public function handleNotify($data) {
        if ($data['result_code'] == "SUCCESS" && $data['return_code'] == "SUCCESS") {
            //修改下载记录的支付状态
            $wechatCode=$data['out_trade_no'];
            $this->changePaymentStatus($wechatCode);
            //删除标识文件
            $this->deleteTagsFile($wechatCode);
            return true;
        } else {
            return false;
        }
    }
    //修改支付状态
    public function changePaymentStatus($rel_wechat_code) {
        $result = model('PySearchLog')->where("slo_wechat_code", "=", $rel_wechat_code)
            ->update(['slo_pay_status' => Status::paySuccess]);
        return $result;
    }


    //删除标识文件
    public function deleteTagsFile($wechatCode){
        try{
            $filePath=config("setting.tagsFilePath").$wechatCode;
            unlink($filePath);
        }catch (Exception $exception){
            Log::write("删除标识文件失败：".$filePath);
            return false;
        }
    }

}
